<?php
namespace app\controller;

use app\BaseController;

use think\facade\Db;
use think\Request;
use think\captcha\facade\Captcha;
use think\cache\driver\Redis;
use think\facade\Cache;

/**
* 用户操作
* 20210720
*/
class User extends BaseController
{
	protected $userInfo;
	protected $request;
	protected $token;
	public function __construct(Request $request){
        $this->request = $request;
        $this->token = $this->request->header('token');
        $requests = new Request_type();
        if($this->token){
            $this->userInfo = $requests->getUserInfo($this->token);
        }
        
	}

	/**
	 * 获取用户基本消息
	 * @return json_encode([type] [description]
	 */
	public function index(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $this->userInfo['count'] = Db::table("t_user")->where("referrer",$this->userInfo['id'])->count();
		return json_encode(array("code"=>200,"msg"=>'成功','data'=>$this->userInfo));
	}

	/**
	 * 修改登录密码
	 * @return json_encode([type] [description]
	 */
	public function reset_password(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
		$data = $this->request->param();

		if(md5(md5($data['password'].$this->userInfo['salt'])) != $this->userInfo['password']){
			return json_encode(array("code"=>'122',"msg"=>'原密碼錯誤'));
		}
		$psw = md5(md5($data['new_password'].$this->userInfo['salt']));
		if(Db::table("t_user")->where("id",$this->userInfo['id'])->save(["password"=>$psw])){
			$redis = new Redis();
			$redis->handler()->select(10);
			$this->userInfo['password'] = $psw;
			$redis->upset($this->token,$this->userInfo);
			return json_encode(array("code"=>200,"msg"=>'成功'));
		}else{
			return json_encode(array("code"=>100,"msg"=>'失敗'));
		}
	}

	/**
	 * 修改支付密码
	 * @return json_encode([type] [description]
	 */
	public function reset_pay_password(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
		$data = $this->request->param();
		if(md5(md5($data['pay_password'].$this->userInfo['pay_salt'])) != $this->userInfo['pay_password']){
			return json_encode(array("code"=>'122',"msg"=>'原密碼錯誤'));
		}
		$psw = md5(md5($data['new_password'].$this->userInfo['pay_salt']));
		if(Db::table("t_user")->where("id",$this->userInfo['id'])->save(["pay_password"=>$psw])){
			$redis = new Redis();
			$redis->handler()->select(10);
			$this->userInfo['pay_password'] = $psw;
			$redis->upset($this->token,$this->userInfo);
			return json_encode(array("code"=>200,"msg"=>'成功'));
		}else{
			return json_encode(array("code"=>100,"msg"=>'失敗'));
		}
	}

	/**
	 * 绑定谷歌验证码 -- 获取谷歌验证码
	 * @return json_encode([type] [description]
	 */
	public function binding_google(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
        //谷歌验证码
        $google=new GoogleAuthenticator();
        $userGoogle = Db::table("t_google_secret")->where("user_id",$this->userInfo['id'])->find();
        if($userGoogle){
        // 	if($userGoogle['status'] == 1){
        // 		return json_encode(array("code"=>100,'msg'=>'失敗'));
        // 	}
        	$secret= $userGoogle['secret'];
        }else{
        	//生成验证秘钥
        	$secret=$google->createSecret();
        	$dataArray = array(
        		"user_id"=>$this->userInfo['id'],
        		"secret"=>$secret,
        		"status"=>0,
        		"create_time"=>date("Y-m-d H:i:s"),
        		"last_time"=>date("Y-m-d H:i:s")
        	);
        	Db::table('t_google_secret')->insert($dataArray);
        }
        //生成验证二维码 $username 需要绑定的用户名
        $qrCodeUrl = $google->getQRCodeGoogleUrl($this->userInfo['user_name'], $secret);

        return json_encode(array("code"=>200,"msg"=>'成功','secret'=>$secret,'qrCodeUrl'=>$qrCodeUrl));
	}

	/**
	 * 校验绑定谷歌验证码
	 * @return json_encode([type] [description]
	 */
	public function check_google(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
		$code = $this->request->param('code');
		$userGoogle = Db::table("t_google_secret")->where("user_id",$this->userInfo['id'])->find();
        if($userGoogle){
        	$google=new GoogleAuthenticator();
        	//$google_secret 存入的谷歌秘钥  ，$code 谷歌动态验证码
        	$checkResult = $google->verifyCode($userGoogle['secret'], $code, 4);
        	if($checkResult){
        		Db::table("t_google_secret")->where("user_id",$this->userInfo['id'])->update(["status"=>1]);
        		Db::table("t_user")->where("id",$this->userInfo['id'])->update(["google_status"=>1]);
        		$redis = new Redis();
				$redis->handler()->select(10);
				$this->userInfo['google_status'] = 1;
				$redis->upset($this->token,$this->userInfo);
				return json_encode(array("code"=>200,"msg"=>'成功'));
        	}else{
        		return json_encode(array("code"=>'117',"msg"=>'穀歌驗證碼錯誤'));
        	}
        }else{
        	return json_encode(array("code"=>100,"msg"=>'失敗'));
        }
	}
	
	/**
	 *获取用户资产
	*@return json_encode([type] [description]
	*/
	public function my_balance(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $balance = Db::table("t_user_coin")->where("user_id",$this->userInfo['id'])->where("coin_name",'USDT')->find();
	    if(!$balance){
	        $address = Db::table("t_trc_address")->where("user_id",$this->userInfo['id'])->value("address");
	        if(!$address){
	            return json_encode(array("code"=>100,"msg"=>'失敗'));   
	        }
            $balance = array(
                'user_id'=>$this->userInfo['id'],
                'coin_name'=>'USDT',
                'bind_address'=>$address,
                'available_balance'=>0,
                'freeze_balance'=>0,
                'receive_freeze_balance'=>0,
                'vip_type'=>0,
                'status'=>0
            );
            Db::table("t_user_coin")->insert($balance); 
	    }
    	$balance['radio'] = 6.5;
    	return json_encode(array("code"=>200,"msg"=>'成功','data'=>$balance));   
	}
	
	/**
	 *获取用户推荐关系
	*@return json_encode([type] [description]
	*/
	public function transductive(){
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
	    $list = Db::table("t_user")->field("id,user_name,register_time")->where("referrer",$this->userInfo['id'])->select()->toArray();
	    if($list){
	        foreach ($list as $k=>$v){
	            $list[$k]['user_name'] = substr_replace($v['user_name'],'****',3,4);
	        }
	    }
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}
	
	public function notice(){
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	    $list = Db::table("t_article")->order("id desc")->page($page,$pageSize)->select()->toArray();
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}
	
	public function notice_details(){
	    $data = $this->request->param();
		$id = $data['id']?$data['id']:0;
		if($id == 0){
		    return json_encode(array("code"=>126,"msg"=>'査詢詳情不能為空'));
		}
	    $list = Db::table("t_article")->where('id',$id)->find();
	    if(!$list){
	        return json_encode(array("code"=>100,"msg"=>'失敗'));
	    }
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}
}